package cn.ac.jaas.isc.vegetable.common.xss.core;

import cn.ac.jaas.isc.vegetable.common.xss.config.VegetableXssProperties;
import cn.ac.jaas.isc.vegetable.common.xss.utils.XssUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author 张高昌
 * @date 2022/4/23 20:35
 * @description: jackson xss 处理
 */
@Slf4j
@RequiredArgsConstructor
public class JacksonXssClean extends JsonDeserializer<String> {

    private final VegetableXssProperties properties;

    private final XssCleaner xssCleaner;

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
        // XSS filter
        String text = p.getValueAsString();
        if (text == null) {
            return null;
        }
        if (XssHolder.isEnabled()) {
            String value = xssCleaner.clean(XssUtil.trim(text, properties.isTrimText()));
            log.debug("Json property value:{} cleaned up by mica-xss, current value is:{}.", text, value);
            return value;
        } else {
            return XssUtil.trim(text, properties.isTrimText());
        }
    }
}
